package com.ruoyi.web.controller.baodao.controller;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.CharsetUtil;
import com.ruoyi.baodao.entity.JDTJ;
import com.ruoyi.baodao.entity.JDTJExample;
import com.ruoyi.baodao.entity.JDTJSetting;
import com.ruoyi.baodao.entity.PayLog;
import com.ruoyi.baodao.mapper.BDMapper;
import com.ruoyi.baodao.mapper.JDTJMapper;
import com.ruoyi.baodao.vo.JDTJFileVO;
import com.ruoyi.baodao.vo.ReceiptDetails;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.DataSourceType;

import com.ruoyi.web.controller.baodao.service.JDTJService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * 交易日志
 */
@Controller
@RequestMapping("/baodao/pay")
public class PayLogController extends BaseController {
    @Autowired
    BDMapper bdMapper;
    @Autowired
    JDTJService jdtjService;
    @Autowired
    JDTJMapper jdtjMapper;




    @GetMapping("/payLog")
    public String payLog(){
        return "baodao/pay/payLog";
    }

    @GetMapping("/statistic")
    public String statistic(){
        return "baodao/pay/statistic";
    }

    // 京东推荐
    @GetMapping("/jdtj")
    public String jdtj(){
        return "baodao/pay/jdtj";
    }


    // 京东推荐设置
    @DataSource(value = DataSourceType.SLAVE)
    @GetMapping("/jdtjSetting")
    public String jdtjSetting(Model modelMap){

        String good_max = "";
        String receipt_max = "";

        // 获取 用户名 和  用户 部门
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        // 取部门编号（门店号）
        sysUser.getDept();
        String shopId = sysUser.getDept().getDeptName();
        List<JDTJSetting> list = bdMapper.queryJDTJSetting(shopId);
        if(list != null && list.size()>0){
            good_max = list.get(0).getGoodMax();
            receipt_max = list.get(0).getReceiptMax();
        }

        modelMap.addAttribute("good_max",good_max);
        modelMap.addAttribute("receipt_max",receipt_max);

        return "baodao/pay/jdtjSetting";
    }

    @PostMapping("/list")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public TableDataInfo queryPayLog(String startTime,String endTime,String p1,String p2,ModelMap modelMap){
        logger.info("startTime: {}, endTime: {}, p1: {}, p2: {}" , startTime,endTime,p1,p2);
        startPage(); //分页
        List<PayLog> payLogList = bdMapper.queryPayLog(startTime,endTime,p1,p2);

        return getDataTable(payLogList);
    }

    @PostMapping("/queryAmount")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public PayLog query(String time){
        logger.info("请求参数: {}",time);
        if(time.equals("1"))   // 昨日
        {
            String date = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                    .withZone(ZoneId.systemDefault()).format(Instant.now().minus(1, ChronoUnit.DAYS));
            PayLog payLog= bdMapper.queryAmountByDay(date,date);
            System.out.println(payLog.toString());
           return payLog;
        }
        if(time.equals("2"))   // 当月
        {

            String date = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                    .withZone(ZoneId.systemDefault()).format(Instant.now());
            PayLog payLog= bdMapper.queryAmountByMonth(date,date);
            return payLog;

        }
        if(time.equals("3"))    // 当年
        {

            String date = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                    .withZone(ZoneId.systemDefault()).format(Instant.now());
            PayLog payLog= bdMapper.queryAmountByYear(date,date);
            return payLog;
        }
        return null;
    }

    // payLog echarts 图数据
    @PostMapping("/queryTransactionDetails")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public List<PayLog> queryTransactionDetails(String time){
        logger.info("请求参数: {}",time);
        if(time.equals("1"))   // 昨日
        {
            String date = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                    .withZone(ZoneId.systemDefault()).format(Instant.now().minus(1, ChronoUnit.DAYS));

            return bdMapper.queryTransactionDetailsByHour(date);
        }
        if(time.equals("2"))   // 当月
        {

            String date = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                    .withZone(ZoneId.systemDefault()).format(Instant.now());
            //PayLog payLog= bdMapper.queryAmountByMonth(date,date);
            return bdMapper.queryTransactionDetailsByDay(date);

        }
        if(time.equals("3"))    // 当年
        {

            String date = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                    .withZone(ZoneId.systemDefault()).format(Instant.now());
            PayLog payLog= bdMapper.queryAmountByYear(date,date);
            return bdMapper.queryTransactionDetailsByMonth(date);
        }
        return null;
    }


    // 小票明细 id = sell_no
    @GetMapping("/receiptDetails/{id}")
    public String receiptDetails(@PathVariable("id") String id, Model modelMap)
    {
        logger.info("请求参数： {}",id);
        //modelMap.put("sellNo",id);
        modelMap.addAttribute("sellNo",id);
        return "baodao/pay/payDetails";
    }

    // 京东推荐 商品明细
    @GetMapping("/jdtj//JDTJDetails/{id}")
    public String jdTJDetails(@PathVariable("id") String id, Model modelMap)
    {
        logger.info("请求参数： {}",id);

        String str1 = id.substring(0, id.indexOf("."));
        //modelMap.put("sellNo",id);
       modelMap.addAttribute("fileName",id);
        return "baodao/pay/jdtjdetails";
    }

    @PostMapping("/receiptDetails/list/{id}")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public TableDataInfo receiptDetails(@PathVariable("id") String id)
    {
        logger.info("参数： " + id);
        startPage();
        List<ReceiptDetails> list = bdMapper.queryReceiptDetails(id);
        return getDataTable(list);
    }

    @PostMapping("/JDTJDetails/list/{id}")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public TableDataInfo jdtjDetails(@PathVariable("id") String id)
    {
        logger.info("参数： " + id);
        startPage();
        //List<JDTJ> list = jdtjService.JDTJList();
        JDTJExample jdtjExample = new JDTJExample();
        JDTJExample.Criteria criteria = jdtjExample.createCriteria();
        criteria.andFileNameEqualTo(id);
        List<JDTJ> list = jdtjMapper.selectByExample(jdtjExample);
        return getDataTable(list);
    }

    //
    @PostMapping("/stopFile")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public AjaxResult stopFileByFileName(String fileName)
    {
        logger.info("停用京东推荐文件： 文件名{}",fileName);
        startPage();
        //List<JDTJ> list = jdtjService.JDTJList();
        JDTJExample jdtjExample = new JDTJExample();
        JDTJExample.Criteria criteria = jdtjExample.createCriteria();
        criteria.andFileNameEqualTo(fileName);
        JDTJ jdtj = new JDTJ();
        jdtj.setStatus("0");
        int result = jdtjMapper.updateByExampleSelective(jdtj,jdtjExample);
        if(result >0)
        return success();
        else
            return error();
    }

    // 收款账本 table 上端统计数据
    @PostMapping("/list2")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public AjaxResult queryPayLog2(String startTime,String endTime,String p1,String p2){
        logger.info("收款账本统计信息参数 ：startTime: {}, endTime: {}, p1: {}, p2: {}" , startTime,endTime,p1,p2);
       // startPage(); //分页
        PayLog payLog = bdMapper.queryPayLog2(startTime,endTime,p1,p2);

        logger.info("收款账本统计信息： " + payLog.toString());
        if(null == payLog)
            return  AjaxResult.success("未查询到数据",null);
        else
        return AjaxResult.success(payLog);
    }


    // 京东推荐 数据导入
    @PostMapping("/jdtj/importCsv")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
/*        String originalFilename = file.getOriginalFilename();
        // csv 文件处理
        ExcelUtil<JDTJ> util = new ExcelUtil<JDTJ>(JDTJ.class);

        List<JDTJ> list = util.importExcel(file.getInputStream());
        logger.info("文件名：" + originalFilename);
        logger.info("待导入数据： " + list.toString());
        if( jdtjService.importData(list,originalFilename))*/

        // 取用户所属门店
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        // 取部门编号（门店号）
        String shopId = sysUser.getDept().getDeptName();

        File tmpfile = null;
        String fileName = null;
        try {
           fileName = file.getOriginalFilename();
            String[] filename = fileName.split("\\.");
            tmpfile=File.createTempFile(filename[0], filename[1]);
            file.transferTo(tmpfile);
            tmpfile.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        List<JDTJ> rows = new ArrayList<>();
        try {
            CsvReader csvReader = CsvUtil.getReader();
             rows = csvReader.read(ResourceUtil.getReader(tmpfile.getPath(), CharsetUtil.CHARSET_GBK), JDTJ.class);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("csv 转 javabean 失败");
            //throw new FileException();
            return AjaxResult.error("文件格式错误");
        }

       if(jdtjService.importData(rows,fileName,shopId))
       {
            return AjaxResult.success("导入成功");
        }
        else {
            return AjaxResult.error("导入失败");
        }
    }

    // 京东推荐商品列表
    @PostMapping("/jdtj/list")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public TableDataInfo list3(JDTJ jdtj){
        //logger.info("startTime: {}, endTime: {}, p1: {}, p2: {}" , startTime,endTime,p1,p2);
        startPage(); //分页
      //  List<JDTJ> list = jdtjService.list();
        List<JDTJFileVO> list = jdtjService.queryJDTJFileList();
        return getDataTable(list);
    }

/*    private File multiToFile(MultipartFile multipartFile) {
        //选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file=File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return file;
    }*/

    // 京东推荐改变状态
    // 京东推荐商品列表
    @PostMapping("/jdtj/changeStatus")
    @DataSource(value = DataSourceType.SLAVE)
    @ResponseBody
    public AjaxResult changeStatus(Long  id,String status){
      /*  //logger.info("startTime: {}, endTime: {}, p1: {}, p2: {}" , startTime,endTime,p1,p2);
        startPage(); //分页
        //  List<JDTJ> list = jdtjService.list();
        List<JDTJFileVO> list = jdtjService.queryJDTJFileList();*/
      logger.info("请求参数{}  {} ",id,status);
        JDTJExample jdtjExample = new JDTJExample();
        JDTJExample.Criteria criteria = jdtjExample.createCriteria();
      //  criteria.andCouponLinkEqualTo(id);
        criteria.andIdEqualTo(id);
        JDTJ jdtj = new JDTJ();
        jdtj.setStatus(status);
        int result = jdtjMapper.updateByExampleSelective(jdtj,jdtjExample);
        if(result > 0) {
            return success();
        }else
        {
            return error();
        }
    }

    // 保存配置
    @PostMapping("/jdtjSetting/save")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult jdtjSettingSave(@Param("good_max") String good_max, @Param("receipt_max") String receipt_max){

        // 获取 用户名 和  用户 部门
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        // 取部门编号（门店号）
        sysUser.getDept();
        String shopId = sysUser.getDept().getDeptName();

        JDTJSetting jdtjSetting = new JDTJSetting();
        jdtjSetting.setShopId(shopId);
        jdtjSetting.setGoodMax(good_max);
        jdtjSetting.setReceiptMax(receipt_max);


        //bdMapper.insertJDTJSetting(jdtjSetting);


        return toAjax(bdMapper.insertJDTJSetting(jdtjSetting));
    }




}
